import { messages, getDefaultPermissionSetOfBook, getDefaultPermissionCompany } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Tabs, Menu, Spin, Icon, message, Radio, Row, Col, Popover, Input, Select } from 'antd'
import Priority from 'components/template/priority'
const Search = Input.Search;
const Option = Select.Option;
import CompactInput from 'components/compact-input'
import subsidyRuleService from 'containers/expense-reimbursement-control/subsidy-rule/subsidy-rule-service'
import 'styles/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule.scss';
import SubsidyDetailList from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/list-subsidy-rule'
import noDataImg from 'images/no-data.png';
class SubsidyRuleSettingList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      defaultValue: null,
      topPermission: 'SET_OF_BOOK',
      status: 'ALL',
      formName: '',
      unsetForms: [],
      setForms: [],
      selectedKeys: null,
      loading: true,
      levelCode: 'COMPANY',
    }
  }

  getPermissionMessage = currentMenuPermission => {
    let { topPermission, defaultValue, levelCode, levelOrgId } = this.state;
    let { loginCompany } = this.props;
    if (currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyCompDTO) {
      let authPolicyCompDTO = currentMenuPermission.currentMenuPermission.authPolicyCompDTO;
      if (authPolicyCompDTO.setOfBooksIds && !!authPolicyCompDTO.setOfBooksIds.length) {
        getDefaultPermissionSetOfBook().then(resp => {
          if (resp.data) {
            topPermission = 'SET_OF_BOOK';
            levelCode = 'SET_OF_BOOK';
            levelOrgId = resp.data.defaultSetOfBooksId;
            defaultValue = {
              range: 'SET_OF_BOOK',
              rangeValue: [{
                setOfBooksName: resp.data.defaultSetOfBooksName,
                setOfBooksId: resp.data.defaultSetOfBooksId
              }]
            }
            this.setState({
              defaultValue,
              levelCode,
              levelOrgId,
              selectedKeys: null,
              companyID: null,
              companyName: null,
              setOfBooksId: resp.data.defaultSetOfBooksId,
              setOfBooksName: resp.data.defaultSetOfBooksName
            }, () => {
              this.getSubsidyControlFormList();
            });
          }
        }).catch(error => {
          message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
        });
      }
      if (!authPolicyCompDTO.setOfBooksIds || authPolicyCompDTO.setOfBooksIds.length === 0) {
        getDefaultPermissionCompany().then(res => {
          topPermission = 'COMPANY';
          levelCode = 'COMPANY';
          levelOrgId = res.id;
          defaultValue = {
            range: 'COMPANY',
            rangeValue: [{
              id: res.id,
              name: res.name,
            }],
          };
          this.setState({
            topPermission,
            defaultValue,
            levelCode,
            levelOrgId,
            selectedKeys: null,
            setOfBooksId: null,
            setOfBooksName: null,
            companyID: res.id,
            companyName: res.name,
          }, () => {
            this.getSubsidyControlFormList();
          });
        })
      }
    }
  };
  getSubsidyControlFormList = (formOID = null) => {
    let { formName, companyID, setOfBooksId } = this.state;
    let params = {
      formName,
      companyId: companyID,
      setOfBooksId,
      valid: true,
    };
    this.setState({
      loading: true,
    });
    subsidyRuleService.getSubsidyControlFormList(params)
      .then(res => {
        if (res && res.data) {
          this.setState({
            loading: false,
            unsetForms: res.data.unsetForms,
            setForms: res.data.setForms,
            selectedKeys: formOID ? formOID : (res.data.setForms && !!res.data.setForms.length ?
                res.data.setForms[0].formOID
                : (res.data.unsetForms && !!res.data.unsetForms.length && res.data.unsetForms[0].formOID ))
          })
        }
      })
      .catch(res => {
        this.setState({
          loading: false,
        });
        message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
      })
  };

  componentWillMount() {
    let { currentMenuPermission } = this.props;
    this.getPermissionMessage(currentMenuPermission)
  }

  handleSearch = val => {
    this.setState({
      formName: val.target.value
    })
  };

  componentWillReceiveProps(nextProps) {
    this.getPermissionMessage(nextProps.currentMenuPermission)
  }

  handleChange = res => {
    if (res && res.rangeValue) {
      switch(res.range) {
        case 'SET_OF_BOOK':
          if (res.rangeValue.setOfBooksId) {
            this.setState({
              levelCode: 'SET_OF_BOOK',
              levelOrgId: res.rangeValue.setOfBooksId,
              setOfBooksId: res.rangeValue.setOfBooksId,
              companyID: null,
              selectedKeys: null,
              companyName: null,
              setOfBooksName: res.rangeValue.setOfBooksName
            }, () => {
              this.getSubsidyControlFormList();
              // this.handleSearchList({ setOfBooksId: res.rangeValue.setOfBooksId })
            })
          } else {
          }
          break;
        case 'COMPANY':
          if (res.rangeValue.id) {
            this.setState({
              levelCode: 'COMPANY',
              levelOrgId: res.rangeValue.id,
              setOfBooksId: null,
              selectedKeys: null,
              setOfBooksName: null,
              companyID: res.rangeValue.id,
              companyName: res.rangeValue.companyName,
            }, () => {
              this.getSubsidyControlFormList();
            });
          }
          break;
      }
    }
  };

  refresh =(formOID)=>{
    formOID && this.getSubsidyControlFormList(formOID);
  }

  handleClick = e => {
    this.setState({ selectedKeys: e.key })
  }

  render() {
    const { status, topPermission, valid, levelCode, levelOrgId, defaultValue, unsetForms, setForms, selectedKeys, loading, formName, setOfBooksId } = this.state;
    let isShowSet =  (status === 'ALL' || status === 'setForms');
    let isShowUnSet = (status === 'ALL' || status === 'unsetForms');
    return (
      <Row className="subsidy-rule-setting-list">
        <Col span={6}>
          <Spin spinning={loading}>
            <div style={{ width: '97%' }}>
              {
                defaultValue && <Priority
                  onlySetOfBooks={topPermission === 'SET_OF_BOOK'}
                  onlyCompany={topPermission === 'COMPANY'}
                  showCompanyComponent={false}
                  showCompany
                  companyProps={{
                    single: true
                  }}
                  top={topPermission}
                  onChange={this.handleChange}
                  defaultValue={defaultValue}
                />
              }
              <CompactInput style={{ marginTop: 10 }}>
                <Select value={status} onChange={(e) => {
                  if (e !== valid) {
                    this.setState({
                      status: e,
                    })
                  }
                }}>
                  <Option value='ALL'>{messages('common.all')/*全部*/}</Option>
                  <Option value='setForms'>{messages('expense-8.key346')/*已设置*/}</Option>
                  <Option value='unsetForms'>{messages('expense-8.key347')/*未设置*/}</Option>
                </Select>
                <Search
                  placeholder={messages('expense-8.key348')/*请输入单据名称*/}
                  onChange={value => this.handleSearch(value)}
                />
              </CompactInput>
            </div>
            <div className="form-list-wrap">
              {isShowSet && <div className="setting-title">{messages('expense-8.key349')/*已设置的单据*/}</div>}
              {isShowSet &&
              <Menu selectedKeys={[selectedKeys]} onClick={this.handleClick}>
                {setForms && setForms.filter(item => {return (item.formName.indexOf(formName) !== -1 )}).map(item => {
                  return <Menu.Item key={item.formOID} className="form-name">
                    {item.formName.length > 17 ?
                      <Popover
                        placement="topLeft"
                        content={item.formName}>
                        {item.formName}
                      </Popover> : <div>{item.formName}</div>}
                  </Menu.Item>
                })}
              </Menu>}
              {isShowUnSet && <div className="setting-title">{messages('expense-8.key350')/*未设置的单据*/}</div>}
              {isShowUnSet &&
              <Menu selectedKeys={[selectedKeys]} onClick={this.handleClick}>
                {unsetForms && unsetForms.filter(item => {return (item.formName.indexOf(formName) !== -1 )}).map(item => {
                  return <Menu.Item key={item.formOID} className="form-name">
                    {item.formName.length > 17 ?
                      <Popover
                        placement="topLeft"
                        content={item.formName}>
                        {item.formName}
                      </Popover> : <div>{item.formName}</div>}
                  </Menu.Item>
                })}
              </Menu>}
            </div>
          </Spin>
        </Col>
        <Col span={18} className="subsidy-detail-list">
          {!selectedKeys && <div
            className="no-data">
            <div className="img-wrap">
              <img src={noDataImg}/>
            </div>
            <div className="mess-wrap">{messages('common.empty.text')/*暂无数据*/}</div>
          </div>}
          {!loading && selectedKeys && <SubsidyDetailList
            formOID={selectedKeys}
            levelCode={levelCode}
            levelOrgId={levelOrgId}
            onChange={this.refresh}
            setOfBooksId={setOfBooksId}
          />}
        </Col>
      </Row>
    )
  }
}

SubsidyRuleSettingList.PropTypes = {
  currentMenuPermission: React.PropTypes.object,
  readonly: React.PropTypes.bool,
};

SubsidyRuleSettingList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    loginCompany: state.login.loginCompany,
    tenantMode: state.main.tenantMode,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}

export default connect(mapStateToProps)(SubsidyRuleSettingList)
